package j5039.whcm.product.service.impl;

import j5039.whcm.product.vo.CategoryTree;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import j5039.whcm.common.utils.PageUtils;
import j5039.whcm.common.utils.Query;

import j5039.whcm.product.dao.CategoryDao;
import j5039.whcm.product.entity.CategoryEntity;
import j5039.whcm.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryTree> queryTree() {
        //查询所有的分类
        List<CategoryEntity> list = this.list();

        List<CategoryTree> treeList = list.stream().filter(c -> c.getParentCid() == 0).map(c -> {
            CategoryTree tree = new CategoryTree();
            tree.setCatId(c.getCatId());
            tree.setName(c.getName());
            tree.setChildren(getChildren(c.getCatId(), list));
            return tree;
        }).collect(Collectors.toList());
        return treeList;
    }

    private List<CategoryTree> getChildren(Long catId, List<CategoryEntity> list) {
        List<CategoryTree> collect = list.stream().filter(c -> c.getParentCid().equals(catId)).map(c -> {
            CategoryTree tree = new CategoryTree();
            tree.setCatId(c.getCatId());
            tree.setName(c.getName());
            if (c.getCatLevel() != 3) {
                tree.setChildren(getChildren(c.getCatId(), list));
            }
            return tree;
        }).collect(Collectors.toList());
        return  collect;
    }


}